import React, { useState, useEffect, useMemo, useCallback } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { Table, TableBody, TableRow, TableCell } from '@/components/ui/table'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger
} from '@/components/ui/tooltip'
import ImageSliceViewer from '@/components/ui/image-slice-viewer'

import { Piece } from '@/types/piece'
import { usePieceStore } from '@/store/piece'
import CreateProps from './CreateProps'
import CreatePiece from './CreatePiece'

interface PieceDialogProps {
  piece?: Piece
  type?: number // 1:装备 2:首饰
  onSelect: (piece: Piece | undefined) => void
  children: React.ReactNode
  recentPieces?: Piece[]
}

// 真实数据由 store 提供

const PieceDialog: React.FC<PieceDialogProps> = ({
  piece,
  type = 1,
  onSelect,
  children,
  recentPieces = []
}) => {
  const [open, setOpen] = useState(false)
  const storePieces = usePieceStore((state) =>
    state.storePieces.filter((p) => p.type === type)
  )
  const loadAllPieces = usePieceStore((state) => state.loadAllPieces)

  useEffect(() => {
    loadAllPieces()
  }, [loadAllPieces])

  // 缓存选择处理函数
  const handleSelect = useCallback(
    (selectedPiece: Piece | undefined) => {
      onSelect(selectedPiece)
      setOpen(false)
    },
    [onSelect]
  )

  // 缓存最近选择的组件
  const recentPiecesComponent = useMemo(() => {
    if (!recentPieces || recentPieces.length === 0) return null

    return (
      <div className="mb-2 h-full">
        <div className="mb-0.5 rounded-md border border-yellow-200 bg-yellow-50 px-2 py-1 text-xs font-semibold leading-tight text-yellow-600">
          ⭐ 最近选择
        </div>
        <div className="grid grid-cols-6 gap-1 overflow-hidden whitespace-nowrap">
          {recentPieces.map((rp, index) => (
            <TooltipProvider key={rp.id}>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div
                    className={`flex h-20 cursor-pointer flex-col items-center overflow-hidden whitespace-nowrap rounded-lg border p-1.5 shadow-md transition hover:border-blue-400 hover:from-blue-50 hover:to-indigo-50 hover:shadow-lg ${
                      piece?.id === rp.id
                        ? 'border-green-600 bg-gradient-to-br from-green-100 to-emerald-100 shadow-lg ring-2 ring-green-400'
                        : index === 0
                          ? 'border-purple-400 bg-gradient-to-br from-purple-100 to-violet-100 shadow-lg ring-2 ring-purple-300'
                          : 'border-orange-300 bg-gradient-to-br from-orange-50 to-amber-50 ring-1 ring-orange-200'
                    }`}
                    onClick={() => handleSelect(rp)}
                    title={rp.name}
                  >
                    <ImageSliceViewer
                      imageSliceId={rp.avatar}
                      alt={rp.name}
                      className="rounded"
                      width={32}
                      height={32}
                    />
                    <span className="mt-0.5 block max-w-full truncate text-[10px] font-medium leading-tight text-gray-700">
                      {rp.alias}
                    </span>
                    <span className="block max-w-full truncate text-[10px] leading-tight text-gray-400">
                      P数: {rp.score}
                    </span>
                  </div>
                </TooltipTrigger>
                <TooltipContent side="top">{rp.describe}</TooltipContent>
              </Tooltip>
            </TooltipProvider>
          ))}
        </div>
      </div>
    )
  }, [recentPieces, piece?.id, handleSelect])

  // 缓存全部碎片的组件
  const allPiecesComponent = useMemo(() => {
    const cols = 6 // 每行6个
    const items = storePieces || []
    const rows = Math.ceil(items.length / cols)

    return (
      <Table className="w-full table-fixed">
        <TableBody>
          {Array.from({ length: rows }).map((_, rowIdx) => (
            <TableRow key={rowIdx}>
              {Array.from({ length: cols }).map((_, colIdx) => {
                const p = items[rowIdx * cols + colIdx]
                if (!p) return <TableCell key={colIdx} />
                return (
                  <TableCell key={colIdx} className="p-1 align-middle">
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <div
                            className={`flex cursor-pointer flex-col items-center overflow-hidden whitespace-nowrap rounded-lg border bg-white p-1.5 shadow-sm transition hover:border-blue-400 hover:shadow-md ${
                              piece?.id === p.id
                                ? 'border-green-600 bg-gradient-to-br from-green-100 to-emerald-100 shadow-lg ring-2 ring-green-400'
                                : 'border-gray-200'
                            }`}
                            onClick={() => handleSelect(p)}
                          >
                            <ImageSliceViewer
                              imageSliceId={p.avatar}
                              alt={p.name}
                              className="rounded"
                              width={32}
                              height={32}
                            />
                            <span className="mt-0.5 block max-w-full truncate text-[10px] font-medium leading-tight text-gray-700">
                              {p.alias}
                            </span>
                            <span className="block max-w-full truncate text-[10px] leading-tight text-gray-400">
                              P数: {p.score}
                            </span>
                          </div>
                        </TooltipTrigger>
                        <TooltipContent side="top">{p.describe}</TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </TableCell>
                )
              })}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    )
  }, [storePieces, piece?.id, handleSelect])

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <div style={{ width: '100%', height: '100%' }}>{children}</div>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>选择/更换碎片</DialogTitle>
        </DialogHeader>
        {/* 最近选择的碎片展示 */}
        {recentPiecesComponent}
        <div className="flex max-h-96 flex-col gap-1 overflow-auto">
          {/* 去掉碎片选项 */}
          {piece && (
            <div className="mb-2 w-full">
              <button
                className="flex w-full items-center justify-center rounded border-2 border-red-300 bg-red-50 p-2 text-red-600 hover:bg-red-100"
                onClick={() => handleSelect(undefined)}
              >
                <span className="text-xs font-medium">去掉碎片</span>
              </button>
            </div>
          )}
          <div className="mb-3 flex items-center justify-between">
            <h3 className="text-sm font-semibold text-gray-700">全部碎片</h3>
            <div className="flex gap-2">
              <CreateProps onSuccess={() => loadAllPieces()} />
              <CreatePiece type={type} onSuccess={() => loadAllPieces()} />
            </div>
          </div>
          {allPiecesComponent}
        </div>
      </DialogContent>
    </Dialog>
  )
}

export default PieceDialog
